//
//  SISSScanViewController.m
//  SISSAPP
//
//  Created by 袁应荣 on 2019/10/11.
//  Copyright © 2019 优房网. All rights reserved.
//

#import "SISSScanViewController.h"
#import "SISSScanResultSucessViewController.h"
#import "SISSNetworkingManager.h"
#import <LBXScan/lbxscanNative.h>

@interface SISSScanViewController ()

@property (nonatomic, strong) UIButton *flashlightBtn;  /** 手电筒开关 */
@property (nonatomic, strong) UILabel *flashlightLab;   /** 手电筒提示文字 */
@property (nonatomic, strong) UILabel *tipLab;  /** 扫描器下方提示文字 */

@end

@implementation SISSScanViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"扫一扫";
    
    UIBarButtonItem *albumItem = [[UIBarButtonItem alloc]initWithTitle:@"相册" style:UIBarButtonItemStylePlain target:self action:@selector(openLocalPhotoAlbum)];
    [albumItem setTintColor:[UIColor blackColor]];
    self.navigationItem.rightBarButtonItem = albumItem;
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [self.view addSubview:self.flashlightBtn];
    [self.view addSubview:self.flashlightLab];
    
    WeakSelf
    [self.flashlightLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(weakSelf.view).offset(-120);
        make.centerX.equalTo(weakSelf.view);
    }];
    
    [self.flashlightBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(weakSelf.flashlightLab.mas_top).offset(-8);
        make.centerX.equalTo(weakSelf.view);
    }];
    
}

- (void)openLocalPhotoAlbum {
    __weak __typeof(self) weakSelf = self;
    [self checkAlbumAuthorizationStatusWithGrand:^(BOOL granted) {
        if (granted) {
            [weakSelf openLocalPhoto];
        }
    }];
}

/*!
 *  打开本地照片，选择图片识别
 */
- (void)openLocalPhoto {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    picker.delegate = self;
    
    // 部分机型可能导致崩溃
    picker.allowsEditing = YES;
    
    [self presentViewController:picker animated:YES completion:nil];
}

//当选择一张图片后进入这里

-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    __block UIImage* image = [info objectForKey:UIImagePickerControllerEditedImage];
    
    if (!image){
        image = [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    
    __weak __typeof(self) weakSelf = self;
    [LBXScanNative recognizeImage:image success:^(NSArray<LBXScanResult *> *array) {
        [weakSelf scanResultWithArray:array];
    }];
    
}

#pragma mark -实现类继承该方法，作出对应处理

- (void)scanResultWithArray:(NSArray<LBXScanResult*>*)array {
    if (!array ||  array.count < 1) {
        [self popAlertMsgWithScanResult:nil];
        
        return;
    }
    
    //经测试，可以ZXing同时识别2个二维码，不能同时识别二维码和条形码
    //    for (LBXScanResult *result in array) {
    //
    //        NSLog(@"scanResult:%@",result.strScanned);
    //    }
    
    LBXScanResult *scanResult = array[0];
    
    NSString*strResult = scanResult.strScanned;
    
    self.scanImage = scanResult.imgScanned;
    
    if (!strResult) {
        
        [self popAlertMsgWithScanResult:nil];
        
        return;
    }
    
    //TODO: 这里可以根据需要自行添加震动或播放声音提示相关代码
    //...
    
    [self showNextVCWithScanResult:scanResult];
}

- (void)popAlertMsgWithScanResult:(NSString*)strResult {
    if (!strResult) {
        
        strResult = @"识别失败";
    }
    
//    __weak __typeof(self) weakSelf = self;
    [self alertActionAlertWithTitle:@"扫码内容" message:strResult];
//    [self reStartDevice];
//    [LBXAlertAction showAlertWithTitle:@"扫码内容" msg:strResult buttonsStatement:@[@"知道了"] chooseBlock:^(NSInteger buttonIdx) {
//
//        [weakSelf reStartDevice];
//    }];
}

- (void)showNextVCWithScanResult:(LBXScanResult*)strResult {
    
    NSLog(@"%@",strResult.strScanned);
    
    [kNetworkNoBaseUrlManager GETWithURLString:strResult.strScanned parameters:@{} success:^(id responseObject) {
        NSLog(@"%@",responseObject);
        SISSScanResultSucessViewController *vc = [[SISSScanResultSucessViewController alloc] init];
        
        if ([responseObject[@"code"] integerValue] == 200) {
            vc.isSuccess = YES;
        } else {
            vc.isSuccess = NO;
            vc.errStr = responseObject[@"data"];
        }
        [self.navigationController pushViewController:vc animated:YES];
    } failure:^(NSError *error) {
        
    }];

}

- (void)openOrCloseFlash {
    [super openOrCloseFlash];
    
    if (self.isOpenFlash) {
        self.flashlightBtn.selected = YES;
        self.flashlightLab.text = @"轻触关闭";
    } else{
       self.flashlightBtn.selected = NO;
       self.flashlightLab.text = @"轻触照亮";
   }
}

/** 手电筒开关 */
- (UIButton *)flashlightBtn {
    if (!_flashlightBtn) {
        _flashlightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//        _flashlightBtn.enabled = NO;
        [_flashlightBtn addTarget:self action:@selector(openOrCloseFlash) forControlEvents:UIControlEventTouchUpInside];
        [_flashlightBtn setBackgroundImage:[UIImage imageNamed:@"qrcode_scan_flashlight_off"] forState:UIControlStateNormal];
        [_flashlightBtn setBackgroundImage:[UIImage imageNamed:@"qrcode_scan_flashlight_on"] forState:UIControlStateSelected];
    }
    return _flashlightBtn;
}

/** 手电筒提示文字 */
- (UILabel *)flashlightLab {
    if (!_flashlightLab) {
        _flashlightLab = [[UILabel alloc] init];
        _flashlightLab.font = [UIFont systemFontOfSize:12];
        _flashlightLab.textColor = [UIColor whiteColor];
        _flashlightLab.text = @"轻触照亮";
        _flashlightLab.textAlignment = NSTextAlignmentCenter;
    }
    return _flashlightLab;
}

@end
